<template>
  <div class="layout">
    <Card>
      <div class="main-con" style="height: 600px">
        <Button icon="md-add" @click="isShowAddModal = true"
          >add the links</Button
        >
        <Input
          type="password"
          icon="ios-search"
          placeholder="Enter search..."
          style="width: 200px; float: right"
        />
        <div class="main-tab">
          <Table border :columns="linkColumns" :data="linkList">
            <template slot="status" slot-scope="{ row }">
              <i-switch
                @on-change="onSwitchChange($event, row.link_id)"
                size="large"
                v-model="row.link_status"
                :true-value="0"
                :false-value="1"
                true-color="#13ce66"
                false-color="#ff4949"
              >
                <span slot="open">展示</span>
                <span slot="close">隐藏</span>
              </i-switch>
            </template>
            <template slot="action" slot-scope="{ row }">
              <Button
                type="primary"
                size="small"
                style="margin-right: 5px"
                @click="editLinkBtn(row)"
                >edit</Button
              >
              <Poptip
                confirm
                title="你确定删除这个友情链接吗?"
                @on-ok="confirmDeleteLink(row.link_id)"
                @on-cancel="$Message.info('取消删除')"
                :transfer="true"
              >
                <Button type="error" size="small">Delete</Button>
              </Poptip>
              <!--              <Button type="error" size="small" @click="delLinkBtn(row)"-->
              <!--                >Delete</Button-->
              <!--              >-->
            </template>
          </Table>
        </div>
      </div>
    </Card>
    <!--    v-model 控制是否显示  -->
    <Modal
      v-model="isShowAddModal"
      title="添加友情链接"
      @on-ok="confirmAddLink"
      @on-cancel="$Message.info('cancel add link')"
    >
      <Form
        ref="addLinkFromRef"
        :label-width="80"
        :model="addForm"
        :rules="addFormRule"
      >
        <FormItem label="Name" prop="name">
          <Input v-model="addForm.name" placeholder="Enter your name" />
        </FormItem>
        <FormItem label="Url" prop="url">
          <Input v-model="addForm.url" placeholder="Enter your url" />
        </FormItem>
      </Form>
    </Modal>
    <!--    修改友情链接弹窗-->
    <Modal
      v-model="isShowEditModal"
      title="修改友情链接"
      @on-cancel="$Message.info('cancel edit link')"
      @on-ok="confirmEditLink"
    >
      <Form
        ref="editLinkFromRef"
        :label-width="80"
        :model="editForm"
        :rules="editFormRule"
      >
        <FormItem label="name" prop="name">
          <Input v-model="editForm.name" />
        </FormItem>
        <FormItem label="url" prop="url">
          <Input v-model="editForm.url" />
        </FormItem>
        <FormItem label="weight" prop="weight">
          <Input v-model="editForm.weight" />
        </FormItem>
        <FormItem label="status" prop="status">
          <i-switch
            size="large"
            v-model="editForm.status"
            :true-value="'0'"
            :false-value="'1'"
            true-color="#13ce66"
            false-color="#ff4949"
          >
            <span slot="open">展示</span>
            <span slot="close">隐藏</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "lay",
  data() {
    const validateAge = (rule, value, callback) => {
      if (value !== 0 && !value) {
        return callback(new Error("Age cannot be empty"));
      }
      // 模拟异步验证效果
      setTimeout(() => {
        if (!Number.isInteger(Number(value))) {
          callback(new Error("Please enter a numeric value"));
        } else {
          if (value < 0) {
            callback(new Error("Must be over 0 "));
          } else if (value > 10) {
            callback(new Error("Must be less then 10 "));
          } else {
            callback();
          }
        }
      }, 100);
    };
    return {
      statusFlag: "",
      addForm: {
        name: "",
        url: ""
      },
      addFormRule: {
        name: [
          {
            required: true,
            message: "The name cannot be empty",
            trigger: "blur"
          }
        ],
        url: [
          {
            required: true,
            message: "The url cannot be empty",
            trigger: "blur"
          },
          {
            type: "url",
            message: "Must be of type url.",
            trigger: "blur"
          }
        ]
      },
      editForm: {
        id: "",
        name: "",
        url: "",
        weight: "0",
        status: "0"
      },
      editFormRule: {
        name: [
          {
            required: true,
            message: "The name cannot be empty",
            trigger: "blur"
          }
        ],
        url: [
          {
            required: true,
            message: "The url cannot be empty",
            trigger: "blur"
          },
          {
            type: "url",
            message: "Must be of type url.",
            trigger: "blur"
          }
        ],
        weight: [{ validator: validateAge, trigger: "blur" }]
      },
      isShowEditModal: false,
      isShowAddModal: false,
      isCollapsed: false,
      isShowdel: false,
      linkColumns: [
        {
          title: "Id",
          key: "link_id"
        },
        {
          title: "Name",
          key: "link_name"
        },
        {
          title: "Url",
          key: "link_url"
        },
        {
          title: "weight",
          key: "link_weight"
        },
        {
          title: "Date",
          key: "link_create_time"
        },
        {
          title: "status",
          slot: "status"
        },
        {
          title: "Action",
          slot: "action",
          width: 150,
          align: "center"
        }
      ],
      linkList: []
    };
  },
  computed: {
    menuitemClasses: function() {
      return ["menu-item", this.isCollapsed ? "collapsed-menu" : ""];
    }
  },
  methods: {
    ...mapActions([
      "fetchAdminLink",
      "saveLink",
      "changeStatus",
      "deleteLink",
      "editLink"
    ]),
    async confirmDeleteLink(id) {
      const res = await this.deleteLink(id);
      if (res.code === 2003) {
        this.$Message.success(`删除<${res.data.link_name}>成功`);
        this.getLink();
      } else {
        this.$Message.error("删除失败");
      }
    },
    async getLink() {
      const res = await this.fetchAdminLink();

      if (res.code === 2000) {
        this.linkList = res.data.content;
      }
    },
    async onSwitchChange(status, id) {
      const res = await this.changeStatus({
        linkStatus: {
          status
        },
        id: id
      });
      if (res.code === 2002) {
        this.$Message.success("更改状态成功");
      } else {
        this.$Message.error("更改状态失败");
      }
    },
    confirmAddLink() {
      this.$refs.addLinkFromRef.validate(async isValid => {
        // 验证不通过
        if (!isValid) {
          this.$Message.error("表单验证不通过");
          setTimeout(() => (this.isShowAddModal = true), 20);
        } else {
          const formData = Object.assign({}, this.addForm);
          this.$refs.addLinkFromRef.resetFields();
          this.addForm = {
            name: "",
            url: ""
          };

          const res = await this.saveLink(formData);
          if (res.code === 2001) {
            this.$Message.success("插入成功");
            await this.getLink();
          } else {
            this.$Message.error("插入失败 message:" + res.message);
          }
        }
      });
    },
    editLinkBtn(row) {
      console.log(row);
      this.editForm.id = row.link_id;
      this.editForm.name = row.link_name;
      this.editForm.url = row.link_url;
      this.editForm.status = row.link_status;
      this.editForm.weight = row.link_weight;
      console.log(this.editForm);
      this.isShowEditModal = true;
    },
    confirmEditLink() {
      this.$refs.editLinkFromRef.validate(async isValid => {
        if (!isValid) {
          this.$Message.error("表单验证不通过");
          setTimeout(() => (this.isShowEditModal = true), 2);
        } else {
          const formData = Object.assign({}, this.editForm);
          this.$refs.editLinkFromRef.resetFields();
          const res = await this.editLink({ formData, id: this.editForm.id });
          this.editForm = {
            id: "",
            name: "",
            url: "",
            status: "0",
            weight: "0"
          };
          if (res.code === 2002) {
            this.$Message.success("修改成功");
            await this.getLink();
          } else {
            this.$Message.error("修改失败 message:" + res.message);
          }
        }
      });
    }
  },

  created() {
    this.getLink();
  }
};
</script>

<style lang="less" scoped>
.menu-item span {
  display: inline-block;
  overflow: hidden;
  width: 69px;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: bottom;
  transition: width 0.2s ease 0.2s;
}
.menu-item i {
  transform: translateX(0px);
  transition: font-size 0.2s ease, transform 0.2s ease;
  vertical-align: middle;
  font-size: 16px;
}
.collapsed-menu span {
  width: 0;
  transition: width 0.2s ease;
}
.collapsed-menu i {
  transform: translateX(5px);
  transition: font-size 0.2s ease 0.2s, transform 0.2s ease 0.2s;
  vertical-align: middle;
  font-size: 22px;
}
.hf h3 {
  color: white;
  line-height: 20px;
}
.hf h4 {
  color: #677170;
  line-height: 20px;
}
.hf hr {
  color: #677170;
}
.inf-edit {
  width: 50vw;
  float: right;
  height: 100px;
}
.main-con {
  padding-top: 30px;
}
.main-tab {
  padding-top: 30px;
  padding-bottom: 30px;
}
</style>
